package cn.kzgg.ymcc.service.impl;

import cn.kzgg.ymcc.domain.KillActivity;
import cn.kzgg.ymcc.domain.KillCourse;
import cn.kzgg.ymcc.mapper.KillCourseMapper;
import cn.kzgg.ymcc.service.IKillActivityService;
import cn.kzgg.ymcc.service.IKillCourseService;
import cn.kzgg.ymcc.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kzgg
 * @since 2022-08-04
 */
@Service
public class KillCourseServiceImpl extends ServiceImpl<KillCourseMapper, KillCourse> implements IKillCourseService {

    @Autowired
    private IKillActivityService killActivityService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 新增秒杀课程
     * @param killCourse
     */
    @Override
    public void save(KillCourse killCourse) {
        //同一课程不能在统一活动
        KillCourse killCourseTmp = selectByKillIdAndCourseId(killCourse.getActivityId(),killCourse.getCourseId());
        AssertUtil.isNull(killCourseTmp,"秒杀课程已存在");

        //新增秒杀课程到活动
        KillActivity killActivity = killActivityService.selectById(killCourse.getActivityId());
        killCourse.setCreateTime(new Date());
        killCourse.setEndTime(killActivity.getEndTime());
        killCourse.setStartTime(killActivity.getStartTime());
        killCourse.setTimeStr(killActivity.getTimeStr());
        insert(killCourse);

    }

    /**
     * 同一课程不能在统一活动
     * @param activityId
     * @param courseId
     * @return
     */
    private KillCourse selectByKillIdAndCourseId(Long activityId, Long courseId) {
        Wrapper<KillCourse> wrapper = new EntityWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("activity_id",activityId);
        return selectOne(wrapper);
    }

    /**
     * 查询所有上架的秒杀课程
     * @return
     */
    @Override
    public List<KillCourse> onlineAll() {
        List<KillCourse> allKillCourse = new ArrayList<>();
        //拿到指定前缀的key
        Set<Object> keys = redisTemplate.keys("activity:*");
        keys.forEach(bigKey->{
            //拿到大key下所有小key里的值
            List values = redisTemplate.opsForHash().values(bigKey);
            //将值存到KillCourse里面
            allKillCourse.addAll(values);

        });
        return allKillCourse;
    }
}
